package com.dididoctor.doctor.Activity.Login;

import android.content.Context;

import com.dididoctor.doctor.Activity.ConstantValue;
import com.dididoctor.doctor.Bean.Token;
import com.dididoctor.doctor.Http.MyHttpResponseHandler;
import com.dididoctor.doctor.MV.BasePresenter;
import com.dididoctor.doctor.MV.BusinessClient;
import com.dididoctor.doctor.MV.Response;
import com.dididoctor.doctor.Utils.SharedPreferencesUtils;
import com.dididoctor.doctor.Utils.Util;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.List;
import java.util.Map;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： LoginPresenter
 * @包名称： com.doudoukeji.service.Activity.Login
 * @创建人： zhanjunjie
 * @创建时间：2016/3/14 15:06
 * @修改人：
 * @修改时间：2016/3/14 15:06
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class LoginPresenter extends BasePresenter {

    private LoginView loginView;
    private Context context;

    public LoginPresenter(Context context, LoginView view) {
        super(context, view);
        this.loginView = view;
        this.context = context;
    }

    /**
     * @param phone 获取验证码
     */
    public void getInvitationCode(String phone) {
        RequestParams params = new RequestParams();
        params.put("phone", phone);
        BusinessClient.post(ConstantValue.intCode, params, new MyHttpResponseHandler(loginView) {

            @Override
            public void onMyResponse(Response response) {
                if (response.isSucceed()) {
                    loginView.getInvitationCode();
                    //TODO 上线需要去掉
//                    loginView.showToastMessage(response.getJson());
                } else {
                    loginView.getInvitationCodeFail();
                    loginView.showToastMessage(response.getMsg());
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                loginView.getInvitationCodeFail();
            }
        });
    }

    public void login(String phone, String checkCode, String inviteCode) {
        RequestParams params = new RequestParams();
//        phone	string	是	电话（前台需要验证，不合法的电话不必调用接口）
//        checkCode	String 	是	验证码
//        inviteCode	String 	是	邀请码
        params.put("phone", phone);
        params.put("checkCode", checkCode);
        params.put("inviteCode", inviteCode);
        BusinessClient.post(ConstantValue.LoginUrl, params, new MyHttpResponseHandler(loginView) {
            @Override
            public void onMyResponse(Response response) {
                if (response.isSucceed()) {
                    //存入文件的用户信息
                    Map<String, Object> doctorInfo = response.getMap("doctorInfo");

                    List<Map<String, Object>> certificate = response.getObjectListData("certificate");
                    if (certificate != null && certificate.size() > 0) {
                        setCertificate(certificate);
                    }
                    setUserInfoData(doctorInfo);
                } else {
                    loginView.showToastMessage(response.getMsg());
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                loginView.loginfail();
            }
        });

    }

    /**
     * 资格证书
     *
     * @param certificate
     */
    private void setCertificate(List<Map<String, Object>> certificate) {

        StringBuffer certificateStrID = new StringBuffer();
        StringBuffer certificateStrUrl = new StringBuffer();
        for (Map<String, Object> map : certificate) {
            certificateStrID.append(Util.toString(Util.toInteger(map.get("picId")) + ","));
            certificateStrUrl.append(Util.toString(map.get("picUrl") + ","));
        }
        certificateStrID.substring(0, certificateStrID.length() - 1);
        certificateStrUrl.substring(0, certificateStrID.length() - 1);

        Token.setCertificateID(certificateStrID.toString());
        Token.setCertificateUrl(certificateStrUrl.toString());
    }

    /**
     * 设置登录信息
     */
    private void setUserInfoData(Map<String, Object> userInfo) {
        Token.setUserId(userInfo.get("userId") + "");
        Token.setPhone(userInfo.get("phone") + "");
        Token.setName(userInfo.get("name") + "");
        Token.setHeadPic(userInfo.get("headPic") + "");
        Token.setSex(userInfo.get("sex") + "");
        Token.setBirth(userInfo.get("birth") + "");
        Token.setIdNo(userInfo.get("idNo") + "");
        Token.setCity(userInfo.get("city") + "");
        Token.setAddress(userInfo.get("hospital") + "");
        Token.setToken(userInfo.get("token") + "");
        Token.setAccId(userInfo.get("accId") + "");
        Token.setAccPwd(userInfo.get("accPwd") + "");
        Token.setOnline(userInfo.get("online") + "");
        Token.setIsSign(userInfo.get("isSign") + "");
        Token.setCallSwitch(userInfo.get("callSwitch") + "");
        Token.setQrcode(userInfo.get("qrcode") + "");
        Token.setIsPass(userInfo.get("isPass") + "");
        Token.setWtId(userInfo.get("wtId") + "");
        String read = SharedPreferencesUtils.getParam(context, "READ", "0");
        if ("1".equals(read)) {
            loginView.intentMainActivity();
        } else {
            loginView.intentDisclaimerActivity();
        }

    }

}
